﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using QBZ.Evaluation.Domains;
using QBZ.Evaluation.Domains.Permissions;
using QBZ.Evaluation.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;

namespace QBZ.Evaluation.Views.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        private readonly UserDomain _user;
        private readonly ILogger<UserController> _logger;
        private readonly RoleDomain _role;


        public UserController(UserDomain user,RoleDomain role, ILogger<UserController> logger)
        {
            //var services = new ServiceCollection();
            //services.AddSingleton<RoleDomain>();//AddSingleton
            //var provider = services.BuildServiceProvider();
            //var _role = provider.GetService<RoleDomain>();
            _user = user;
            _logger = logger;
            _role = role;
            
            //_init = init;

        }

        [PermissionFilter(UserLevel.regUser)]
        public IActionResult Index()
        {
            return View(_user.GetAll());
        }


        [PermissionFilter(UserLevel.superAdmin)]
        public IActionResult AddUser(UserModel user)
        {
            return Json(_user.AddUser(user));
        }


        [AllowAnonymous]
        public IActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                return Json(_user.Login(model, HttpContext));
            }
            else
            {
                var res = new ResponseModel(ErrReason.WrongDataFormat);
                res.status.msg += ":" + ModelState.FirstOrDefault();
                return Json(res);
            }
        }

        [PermissionFilter(UserLevel.regUser)]
        public IActionResult MergeAccount(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userId = 0;
                object userLevel = UserLevel.regUser;
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    int.TryParse(HttpContext.User.FindFirst(_ => _.Type == "UserId").Value, out userId);
                    if (!Enum.TryParse(typeof(UserLevel), HttpContext.User.FindFirst(_ => _.Type == "UserLevel").Value, out userLevel))
                    {
                        userLevel = UserLevel.noLogin;
                    }
                }
                return Json(_user.MargeAccount(model, userId, (UserLevel)userLevel));
            }
            else
            {
                var res = new ResponseModel(ErrReason.WrongDataFormat);
                res.status.msg += ":" + ModelState.FirstOrDefault();
                return Json(res);
            }
        }

        [PermissionFilter(UserLevel.superAdmin)]
        public IActionResult Infos(string filter = "{}", string sort = "UserId", string order = "asc", string multiSort = "", int offset = 0,int limit =15)
        {
            var res = new ResponseModel(ErrReason.Ok);
            if ( string.IsNullOrWhiteSpace(multiSort))
            {
                multiSort = "[{\"sortName\":\"" + sort + "\",\"sortOrder\":\"" + order + "\"}]";
            }
            res.result = _user.getUsersInfo(filter, multiSort,offset,limit);
            return Json(res);
        }

        [PermissionFilter(UserLevel.regUser)]
        public IActionResult Info()
        {
            var res = new ResponseModel();
            var result = new UserInfo();
            var userIdClaim = HttpContext.User.FindFirst(_ => _.Type == "UserId");
            if (userIdClaim != null)
            {
                var userId = int.Parse(userIdClaim.Value);
                var user = _user.FindUser(userId);
                if (user == null)
                {
                    res.status = new ResponseStatusModel(ErrReason.UserNotExist);
                }
                else
                {
                    result.baseInfo = user;
                    result.menu = _user.GetMenus((UserLevel)result.baseInfo.UserLevel);
                    result.role = _role.GetAll();
                    res.result = result;
                    res.status = new ResponseStatusModel(ErrReason.Ok);
                }
            }
            else
            {
                res.status = new ResponseStatusModel(ErrReason.AccessDenied);
            }
            return Json(res);
        }

        [PermissionFilter(UserLevel.superAdmin)]
        public IActionResult ResetPassword(int userId)
        {
            _user.ResetPassword(userId);
            return Json(new ResponseModel(ErrReason.Ok));
        }

    }
}